import {httpAction} from '@/api/manage'
import Sortable from 'sortablejs'
import {randomString} from "../utils/util";

export const YchVxeTableMixin = {
  data() {
    return {
      title: this.$t('m.common.label.operate'),
      visible: false,
      form: this.$form.createForm(this),
      spinning: 0,
      model: {},
      sortables: {},
      labelCol: {
        xs: {span: 24},
        sm: {span: 6}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      }
    }
  },
  methods: {
    add() {
      if (typeof this.addBefore === 'function') {
        this.addBefore()
      }
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true

      if (typeof this.editAfter === 'function') {
        this.editAfter()
      }
    },
    copy (record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      if (typeof this.editAfter === 'function') {
        this.editAfter()
      }
      this.model.id = undefined
    },
    async handleOk() {
      // 触发表单验证
      this.form.validateFields(async (err, values) => {
        if (!err) {
          let httpUrl = '';
          let method = '';
          if (!this.model.id) {
            httpUrl += this.url.add;
            method = 'post';
          } else {
            httpUrl += this.url.edit;
            method = 'put';
          }

          let formData = Object.assign(this.model, values);
          if (typeof this.beforeSave === 'function') {
            formData = await this.beforeSave(formData)
            if (!formData) {
              return
            }
          }

          this.spinning++
          httpAction(httpUrl, formData, method).then((res) => {
            if (res.success) {
              this.messageUtil.success(res.message)
              this.$emit('ok', formData)
              this.close()
            } else {
              this.messageUtil.warning(res.message)
            }
          }).finally(() => {
            this.spinning--
          })
        }
      })
    },
    async getTableDataSource($table, dataSource) {
      const errMap = await $table.fullValidate(true).catch(errMap => errMap)
      if (errMap) {
        const msgList = []
        Object.values(errMap).forEach(errList => {
          errList.forEach(params => {
            const {rowIndex, column, rules} = params
            rules.forEach(rule => {
              msgList.push(this.$t('m.eform.formDesign.label.vxe_error', [rowIndex + 1, column.title, rule.message]))
            })
          })
        })
        this.$message.warning({
          icon: () => {
            return null
          },
          content: (
            <div style="color: red; max-hclassName: 400px; overflow: auto;">
              {
                msgList.map(msg => <div>{msg}</div>)
              }
            </div>
          )
        })
        return false
      } else {
        return dataSource
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
      if (typeof this.afterClose === 'function') {
        this.afterClose()
      }
      this.spinning = 0
      this.model = {}
    },
    handleCancel() {
      this.close()
    },
    async insertRow(tableId, dataSource, initData, activeCell, index) {
      const $table = this.$refs[tableId]
      let id = randomString(32)
      const record = {
        id: id,
        ...initData
      }
      if (typeof index === "undefined" || index === -1) {
        dataSource.push(record)
      } else {
        dataSource.splice(index, 0, record)
      }
      if (activeCell) {
        await $table.setActiveCell(record, activeCell)
      }
    },
    deleteRow(tableId, dataSource, key) {
      const $table = this.$refs[tableId]
      const selectRecords = $table.getCheckboxRecords()
      if (selectRecords.length === 0) {
        this.messageUtil.warning("没有选中数据")
        return
      }
      const idKey = key || 'id'

      const temp = {}
      dataSource.forEach((item, index) => {
        temp[item[idKey]] = index
      })
      let count = 0;
      selectRecords.forEach(item => {
        dataSource.splice(temp[item[idKey]] - count, 1)
        count++
      })
    },
    rowDrop(tableId, callback) {
      if (this.sortables[tableId]) {
        return
      }
      this.$nextTick(() => {
        const xTable = this.$refs[tableId]
        const sortableTool = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
          handle: '.drag-btn',
          onEnd: ({newIndex, oldIndex}) => {
            if (typeof callback === 'function') {
              callback.apply(this, [newIndex, oldIndex])
            }
          }
        })
        this.sortables[tableId] = sortableTool
      })
    },
    afterRowDrop(newIndex, oldIndex, dataSource) {
      const currRow = dataSource.splice(oldIndex, 1)[0]
      dataSource.splice(newIndex, 0, currRow)
    },
    resetOrderNum(dataSource, orderNumId) {
      dataSource.forEach((item, index) => {
        item[orderNumId || 'orderNum'] = index + 1
      })
    },
  },
  beforeDestroy() {
    Object.keys(this.sortables).forEach(key => {
      this.sortables[key].destroy()
    })
    this.sortables = {}
  }
}
